"use client";
import { useEffect, useState } from "react";
import {
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  message,
  Card,
  Select,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  MinusCircleOutlined,
} from "@ant-design/icons";
import {
  coralClassControllerCreate,
  coralClassControllerUpdate,
  coralClassControllerRemove,
  coralClassControllerFindAll,
} from "@/app/servers/api/coralClass";
import { SingleUpload } from "@/app/components/single-upload/single-upload";

export default function CoralClassPage() {
  const [form] = Form.useForm();
  const [data, setData] = useState<API.ReturnCoralClass[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);

  // 初始化获取数据
  const fetchData = async () => {
    setLoading(true);
    try {
      const response = await coralClassControllerFindAll();
      setData(response.data || []);
    } catch {
      message.error("加载数据失败");
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    fetchData();
  }, []);

  const columns: ColumnsType<API.ReturnCoralClass> = [
    {
      title: "课程标题",
      dataIndex: "classTitle",
      width: 80,
    },
    {
      title: "课程简介",
      dataIndex: "classDesc",
      width: 150,
      render(value) {
        return value.slice(0, 50) + "...";
      },
    },
    {
      title: "视频名称",
      dataIndex: ["video", "name"],
      width: 200,
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      width: 180,
      render: (text) => (text ? new Date(text).toLocaleString() : "-"),
    },
    {
      title: "更新时间",
      dataIndex: "updatedAt",
      width: 180,
      render: (text) => (text ? new Date(text).toLocaleString() : "-"),
    },
    {
      title: "操作",
      key: "action",
      width: 150,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    form.resetFields();
    setModalVisible(true);
    setEditingId(null);
  };

  const handleEdit = (record: API.ReturnCoralClass) => {
    const questions = JSON.parse(record.questionJson);
    form.setFieldsValue({
      ...record,
      questions,
    });
    setEditingId(record.id);
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: "确认删除",
      content: "确定要删除这条课程记录吗？",
      onOk: async () => {
        try {
          await coralClassControllerRemove({ id: String(id) });
          message.success("删除成功");
          fetchData();
        } catch {
          message.error("删除失败");
        }
      },
    });
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      // 序列化问题配置
      const questions = values.questions || [];
      const questionJson = JSON.stringify(questions);

      const submitData = {
        ...values,
        questionJson,
        videoId: values.video.id,
      };
      delete submitData.video;
      delete submitData.questions;
      if (editingId) {
        await coralClassControllerUpdate(
          { id: String(editingId) },
          submitData as API.UpdateCoralClassDto
        );
      } else {
        await coralClassControllerCreate(submitData as API.CreateCoralClassDto);
      }
      setModalVisible(false);
      message.success(editingId ? "更新成功" : "创建成功");
      fetchData();
    } catch {
      message.error("操作失败");
    }
  };

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          新建课程
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
      />

      <Modal
        title={editingId ? "编辑课程" : "新建课程"}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => {
          setModalVisible(false);
        }}
        destroyOnClose
        width={800}
      >
        <Form form={form} layout="vertical" initialValues={{ questions: [{}] }}>
          <Form.Item required name="classTitle" label="课程标题">
            <Input />
          </Form.Item>
          <Form.Item required name="classDesc" label="课程简介">
            <Input.TextArea rows={4} />
          </Form.Item>
          <Form.Item
            label="课程视频"
            required
            help="支持 mp4、webm 等格式，文件小于 500MB"
            name="video"
          >
            <SingleUpload listType="text" maxSize={500} accept="video/*" />
          </Form.Item>
          <div className="text-lg font-bold mb-4 mt-8">问题配置</div>
          <Form.List name="questions">
            {(fields, { add, remove }) => (
              <div className="space-y-4">
                {fields.map((field, index) => (
                  <Card
                    key={field.key}
                    title={`问题 ${index + 1}`}
                    extra={
                      fields.length > 1 && (
                        <Button
                          type="text"
                          danger
                          icon={<MinusCircleOutlined />}
                          onClick={() => remove(field.name)}
                        >
                          删除
                        </Button>
                      )
                    }
                  >
                    <Form.Item
                      {...field}
                      label="问题内容"
                      name={[field.name, "questionText"]}
                      rules={[{ required: true, message: "请输入问题内容" }]}
                    >
                      <Input.TextArea rows={2} placeholder="请输入问题内容" />
                    </Form.Item>

                    <div className="grid grid-cols-2 gap-4">
                      <Form.Item
                        {...field}
                        label="选项A"
                        name={[field.name, "optionA"]}
                        rules={[{ required: true, message: "请输入选项A" }]}
                      >
                        <Input placeholder="请输入选项A" />
                      </Form.Item>

                      <Form.Item
                        {...field}
                        label="选项B"
                        name={[field.name, "optionB"]}
                        rules={[{ required: true, message: "请输入选项B" }]}
                      >
                        <Input placeholder="请输入选项B" />
                      </Form.Item>

                      <Form.Item
                        {...field}
                        label="选项C"
                        name={[field.name, "optionC"]}
                        rules={[{ required: true, message: "请输入选项C" }]}
                      >
                        <Input placeholder="请输入选项C" />
                      </Form.Item>

                      <Form.Item
                        {...field}
                        label="选项D"
                        name={[field.name, "optionD"]}
                        rules={[{ required: true, message: "请输入选项D" }]}
                      >
                        <Input placeholder="请输入选项D" />
                      </Form.Item>
                    </div>

                    <Form.Item
                      {...field}
                      label="正确答案"
                      name={[field.name, "correctOption"]}
                      rules={[{ required: true, message: "请选择正确答案" }]}
                    >
                      <Select placeholder="请选择正确答案">
                        <Select.Option value="A">A</Select.Option>
                        <Select.Option value="B">B</Select.Option>
                        <Select.Option value="C">C</Select.Option>
                        <Select.Option value="D">D</Select.Option>
                      </Select>
                    </Form.Item>
                  </Card>
                ))}

                <Button
                  type="dashed"
                  onClick={() => add()}
                  block
                  icon={<PlusOutlined />}
                >
                  添加问题
                </Button>
              </div>
            )}
          </Form.List>
        </Form>
      </Modal>
    </div>
  );
}
